from django.shortcuts import render

from django.http import HttpResponse,JsonResponse

from .. models import Types
from django.contrib.auth.decorators import permission_required


#封装查询函数
def gettypes():
    #模型提供
    obs = Types.objects.extra(select = {'path':'concat(path,id)'}).order_by('path')
    #循环处理父类名

    for x in obs:
        if x.pid != 0:
            if x.pid >= 3:
                x.name = "　　|---"+x.name

            x.name = "　　|---"+x.name
            ob = Types.objects.get(id = x.pid)
            x.pname = ob.name
    return obs
#分类添加
@permission_required('myadmin.insert_types',raise_exception=True)

def add(request):

    con = {'typelist':gettypes()}
    return render(request,'admin/type/add.html',con)

#分类执行添加
@permission_required('myadmin.insert_types',raise_exception=True)

def insert(request):
    
    #获取数据
    data = request.POST.dict()

    del data['csrfmiddlewaretoken']
    #判断添加的是否是顶级数据

    if data['pid'] == '0':
        data['path'] = '0,'
    else:

        #不是顶级分类
        #现获取父级的path
        ob = Types.objects.get(id=data['pid'])
        data['path'] = ob.path+data['pid']+','

    #执行添加

    ob = Types.objects.create(**data)

    if ob:
        return HttpResponse('<script>alert("分类添加成功");location.href="/admin/types/index/"</script>')
    else:
        return HttpResponse('<script>alert("分类添加失败");history.back(-1)"</script>')

@permission_required('myadmin.show_types',raise_exception=True)

#分类展示页面
def index(request):

    obs = Types.objects.filter()

    context = {'typelist':gettypes()}



    types = request.GET.get('type',None)
    if types:
        #获取搜索的关键字
        keywords = request.GET.get('keywords',None)

        

        

        
        data = {types+'__contains':keywords}

        obs = obs.filter(**data)

        context = {'typelist':obs}


    
    
    #获取当前页的页数
    pageindex = request.GET.get('p',1)

    from django.core.paginator import Paginator

    #实例化分页对象

    p = Paginator(obs,2)

    obs = p.page(pageindex)

    context = {'typelist':obs}

    

    # 加载模板
    return render(request,'admin/type/index.html',context)


#删除
@permission_required('myadmin.del_types',raise_exception=True)

def delete(request):
    tid = request.GET['id']

    #查看当前类下是否有子类

    num = Types.objects.filter(pid=tid).count()

    if num:
        return JsonResponse({'code':1,'msg':'当前类下还有子类,不能删除'}) 
    
    ob = Types.objects.get(id=tid)


    res = ob.delete()

    
    if res:
        return JsonResponse({'code':0,'msg':'删除成功'})
    else:
        return JsonResponse({'code':3,'msg':'删除失败'})

#修改
@permission_required('myadmin.edit_types',raise_exception=True)

def edit(request,tid):
    
    #获取数据

    ob = Types.objects.get(id=tid)

    #分配数据

    con = {'tl':ob}

    #判断请求方式

    if request.method == 'GET':

        return render(request,'admin/type/edit.html',con)

    elif request.method == 'POST':

        #执行修改
        try:
            ob.name = request.POST['name']
            ob.save()
            return HttpResponse('<script>alert("分类修改成功");location.href="/admin/types/index/"</script>')
        except:
            return HttpResponse('<script>alert("分类修改成功");location.href="/admin/types/index/"</script>')
